home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1995 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.5 KB  |  71 lines

  1. Newsgroups: comp.lang.c
  2. Path: news.sprintlink.net!eskimo!news
  3. From: mag@eskimo.com (mAg)
  4. Subject: Re: How to access memory allocated  in function
  5. X-Nntp-Posting-Host: tia1.eskimo.com
  6. Message-ID: <DLD5wM.KK5@eskimo.com>
  7. Sender: news@eskimo.com (News User Id)
  8. Organization: *.*
  9. X-Newsreader: WinVN 0.93.10
  10. References: <4ddbe3$so3@josie.abo.fi>
  11. Date: Thu, 18 Jan 1996 06:26:46 GMT
  12.  
  13. In article <4ddbe3$so3@josie.abo.fi> (Mon, 15 Jan 96 13:46:17 GMT), csundqvi@abo.fi 
  14. says :
  15. >
  16. >Hello
  17. >
  18. >
  19. >How can i access memory allocated dynamically in a function after i leave the 
  20. >function, something like this:
  21. >
  22. >main()
  23. >{
  24. >int *p;
  25. >sub(p);
  26. >}
  27. >
  28. >void sub(int *p)
  29. >{
  30. > p = malloc(.....);
  31. >}
  32. >
  33. >Thanks !
  34.  
  35. There is no way to free that memory unless you do it in the sub itself. Anyway in the 
  36. above example the local copy of 'p' in sub() will hold the result of malloc() and 
  37. forget it as soon as the function terminates.
  38.  
  39. here is an example how to allocate in a function and use the memory in the caller.
  40.  
  41. #include <stdlib.h>
  42.  
  43. void sub(int **pp)
  44. {
  45. *pp = malloc(.......);
  46. }
  47.  
  48. int main(void)
  49. {
  50. int *p;
  51. sub(&p);
  52. /* do whatever with block pointed by p */
  53.  
  54. ...
  55. ...
  56. ...
  57.  
  58. free(p);
  59. }
  60.  
  61.  
  62. -- 
  63. /* --------------------------------------------------------
  64.                       MAG@ESKIMO.COM
  65. http://www.eskimo.com/~mag/index.html
  66. ***********************************************************
  67. To understand recursion one must first understand recursion
  68. ***********************************************************
  69. -------------------------------------------------------- */
  70.  
  71.